package com.attendancesystem.controller;


import com.attendancesystem.model.Unit;
import com.attendancesystem.service.UnitService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "AddUnitController", value = "/AddUnitController")
public class AddUnitController extends HttpServlet {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        JsonNode rootNode = objectMapper.readTree(request.getReader());
        PrintWriter out = response.getWriter();
        String unitName = rootNode.get("unitName").asText();
        String unitDesc = rootNode.get("unitDesc").asText();
        String unitDuration = rootNode.get("unitDuration").asText();
        String courseId= rootNode.get("courseId").asText();
        Unit unit = new Unit();
        unit.setUnitName(unitName);
        unit.setUnitDescription(unitDesc);
        unit.setUnitDuration(Integer.parseInt(unitDuration));
        unit.setCourseId(Integer.parseInt(courseId));
        UnitService unitService = new UnitService();
        if (unitService.addUnit(unit)){
            out.print("{\"status\":\"success\"}");
        }else {
            out.print("{\"status\":\"failed\"}");
        }




    }
}
